package com.wz.dhs.model.common;

import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.slf4j.MDC;

import java.io.Serializable;

/**
 * 统一报文响应返回
 *
 */
@ApiModel("统一响应消息报文")
@Data
public class Result<T>  implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 状态码
     */
    @ApiModelProperty(
            value = "状态码",
            required = true
    )
    private String code;

    /**
     * 消息内容
     */
    @ApiModelProperty(
            value = "消息内容",
            required = true
    )
    private String msg;
    @ApiModelProperty(
            value = "时间戳",
            required = true
    )

    /**
     * 时间戳
     */
    private long time;

    /**
     * 流水号
     */
    private String traceId;

    /**
     * 业务返回数据
     */
    @ApiModelProperty("业务数据")
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private T data;

    public Result() {
        this.time = System.currentTimeMillis();
    }

    public Result(IResultCode resultCode) {
        this(resultCode, (T) null, resultCode.getMsg());
    }

    public Result(IResultCode resultCode, String msg) {
        this(resultCode, (T) null, msg);
    }

    public Result(IResultCode resultCode, T data) {
        this(resultCode, data, resultCode.getMsg());
    }

    public Result(IResultCode resultCode, T data, String msg) {
        this(resultCode.getCode(), data, msg);
    }

    public Result(String code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
        this.time = System.currentTimeMillis();
        this.traceId = MDC.get("traceId");
    }

    public static <T> Result<T> success(String msg) {
        return new Result(ResultCode.SUCCESS, msg);
    }

    public static <T> Result<T> data(T data) {
        return data(data, "处理成功");
    }

    public static <T> Result<T> data(T data, String msg) {
        return data(ResultCode.SUCCESS.code, data, msg);
    }

    public static <T> Result<T> data(String code, T data, String msg) {
        return new Result(code, data, data == null ? "承载数据为空" : msg);
    }

    public static <T> Result<T> fail() {
        return new Result(ResultCode.FAILURE, ResultCode.FAILURE.getMsg());
    }

    public static <T> Result<T> fail(String msg) {
        return new Result(ResultCode.ERROR, msg);
    }

    public static <T> Result<T> fail(String code, String msg) {
        return new Result(code, (Object)null, msg);
    }

    public static <T> Result<T> fail(IResultCode resultCode) {
        return new Result(resultCode);
    }

    public static <T> Result<T> fail(IResultCode resultCode, String msg) {
        return new Result(resultCode, msg);
    }

    public static <T> Result<T> condition(boolean flag) {
        return flag ? success("处理成功") : fail("处理失败");
    }

}
